#!/bin/sh -e

okabi | (
  while read abi
  do

    rm -f cpucycles.o cpucycles.h
    
    (
      case "$abi" in
        ppc*)
          echo powerpccpuinfo
          echo powerpcmacos
	  ;;
        amd64*)
          echo amd64tscfreq
          echo amd64cpuinfo
          echo amd64cpuspeed
	  ;;
        x86*)
          echo x86tscfreq
          echo x86cpuinfo
          echo x86cpuspeed
          echo x86estimate
	  ;;
	cell*)
          echo celllinux
	  ;;
	sparc*)
          echo sparccpuinfo
          echo sparc32cpuinfo
	  ;;
	mips*)
          echo mips
	  ;;
	hppa*)
          echo hppapstat
	  ;;
	alpha*)
          echo alpha
	  ;;
	sgi*)
          echo sgi
	  ;;
	arm*)
	  echo cortex
          echo dev4ns
	  ;;
      esac

      echo apple
      echo amd64tscfreq
      echo amd64cpuinfo
      echo amd64cpuspeed
      echo x86tscfreq
      echo x86cpuinfo
      echo x86cpuspeed
      echo x86estimate
      echo ia64cpuinfo
      echo powerpccpuinfo
      echo powerpcmacos
      echo celllinux
      echo sparccpuinfo
      echo sparc32cpuinfo
      echo mips
      echo hppapstat
      echo alpha
      echo sgi
      echo cortex
      echo dev4ns
      echo perfevent
      echo monotoniccpuinfo
      echo monotonic
      echo gettimeofday
    ) | (
      while read n
      do
        okc-$abi | (
          while read c
          do
            echo "=== `date` === Trying $n.c with $c..." >&2
            rm -f test cpucycles-impl.o cpucycles-impl.h cpucycles-impl.c
            cp $n.c cpucycles-impl.c || continue
            cp $n.h cpucycles-impl.h || continue
            $c -c cpucycles-impl.c || continue
            $c -o test test.c cpucycles-impl.o || continue
            killafter 300 ./test || continue
            echo "=== `date` === Success. Using $n.c." >&2
            mkdir -p lib/$abi
            mv cpucycles-impl.o lib/$abi/cpucycles.o
            mkdir -p include/$abi
            mv cpucycles-impl.h include/$abi/cpucycles.h
            exit 0
          done
          exit 111
        ) && exit 0
      done
      exit 111
    ) || (
      echo ===== Giving up. >&2
      rm -f test cpucycles-impl.o cpucycles-impl.h cpucycles-impl.c
      exit 111
    ) || exit 0

  done
  exit 0
) || exit 111
